package com.cim.storage;


import com.cim.utils.Md5CaculateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Path;

/**
 * 提供存储服务类，所有存储服务均由该类对外提供
 */
@Component
public class StorageService {
    private final Logger logger = LoggerFactory.getLogger(StorageService.class);

    @Autowired
    private LocalStorage localStorage=new LocalStorage();


    /**
     * 存储一个文件对象
     *
     * @param inputStream   文件输入流
     * @param contentLength 文件长度
     * @param contentType   文件类型
     * @param fileName      文件索引名
     */
    public String store(InputStream inputStream, long contentLength, String contentType, String fileName) {
        logger.info("存储文件,fileName:{},contentLength:{},contentType:{}", fileName, contentLength, contentType);
        String suffix = getSuffix(fileName);
        if(contentType.length() > 20){
            logger.warn("文件类型错误");
            contentType = suffix;
        }
        if(contentType.length() > 20) {
            logger.error("文件类型错误,无法上传,filename:{}, type:{}", fileName, contentType);
        }
        //保存文件为temp
        localStorage.store(inputStream, 0L, null, "temp");
        Resource resource = localStorage.loadAsResource("temp");
        String md5Key = null;
        try {
            md5Key = Md5CaculateUtil.getMD5(resource.getFile());
        } catch (IOException e) {
            e.printStackTrace();
            logger.error("store. md5 error");
        }
        String md5FileName = md5Key + suffix;
        localStorage.move("temp",md5FileName);
        return md5FileName;
    }

    //获取文件拓展名
    public static String getSuffix(String name){
        if(name==null){
            return ".mp4";
        }
        int index = name.lastIndexOf('.');
        if(index==-1){
            return ".mp4";
        }
        return name.substring(index);
    }

    //获取文件路径
    public Path load(String name){
        Path path=localStorage.load(name);
        if(!path.toFile().exists()){
            return null;
        }
        return path;
    }

    public void delete(String name){
        Path path=load(name);
        path.toFile().delete();
    }
}
